package com.vtuzx.kingdee.xqc_core.dao;

import com.vtuzx.core.constant.IVtuzxConst;
import com.vtuzx.core.db.mongo.impl.VtuzxDaoImpl;
import com.vtuzx.core.utils.VtuzxUtil;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 对接系统接口履历Dao
 */
@Component
public class BomDao extends VtuzxDaoImpl {
    /** 集合名称 */
    public static final String NAME = "t_bom";

    public BomDao() {
        super(NAME);
    }

    public Iterator<Document> getChildList(Criteria cond, int pageIndex, int pageSize) {
        List<Document> pipes = new ArrayList<>();
        pipes.add(new Document("$unwind", new Document("path", "$childList")));
        pipes.add(new Document("$lookup", new Document("from", MaterialDao.NAME).append("foreignField", "fNumber").append("localField", "childList.childMaterialNo").append("as", "material")));
        pipes.add(new Document("$unwind", new Document("path", "$material")));
        pipes.add(new Document("$match", cond.and("material.F_ora_SFFX").is(true).getCriteriaObject()));
        pipes.add(new Document("$group",
                new Document("_id", new Document("materialNo", "$childList.childMaterialNo")
                        .append("materialName", "$childList.childMaterialName")
                        .append("materialModel", "$childList.childMaterialModel")
                        .append("numerator", "$childList.numerator")
                        .append("denominator", "$childList.denominator")
                        .append("scraprate", "$childList.scraprate")
                        .append("unit", "$childList.childUnitNumber")
                        .append("unitName", "$childList.childUnitName")
                )
                        .append("count", new Document("$sum", 1))));
        pipes.add(new Document("$skip", pageIndex * pageSize));
        pipes.add(new Document("$limit", pageSize));
        return aggregate(pipes);
    }

    public Iterator<Document> getList(Criteria cond,Document sort, int pageIndex, int pageSize) {
        List<Document> pipes = new ArrayList<>();
        pipes.add(new Document("$match", cond.getCriteriaObject()));
        if (sort != null) {
            pipes.add(new Document("$sort", sort));
        }
        pipes.add(new Document("$lookup", new Document("from", MaterialDao.NAME).append("foreignField", "fNumber").append("localField", "materialNo").append("as", "material")));
        pipes.add(new Document("$unwind", new Document("path", "$material")));
        pipes.add(new Document("$match", Criteria.where("material.F_ora_SFBCP").is(true).getCriteriaObject()));
        pipes.add(new Document("$skip", pageIndex * pageSize));
        pipes.add(new Document("$limit", pageSize));
        return aggregate(pipes);
    }

}